package com.junzhiit.nengji.cms.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.junzhiit.nengji.cms.service.ChainTypeService;
import com.junzhiit.nengji.cms.web.exception.ChainNotFoundException;
import com.junzhiit.nengji.cms.web.exception.TypeIsExistException;
import com.junzhiit.nengji.cms.web.exception.TypeNotFoundException;
import com.junzhiit.nengji.cms.web.util.Constants;
import com.junzhiit.nengji.cms.web.util.OrderNumberUtils;
import com.junzhiit.nengji.cms.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.cms.web.vo.ChainTypeAddVO;
import com.junzhiit.nengji.cms.web.vo.ChainTypeVO;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.SystemUserSessionVO;
import com.junzhiit.nengji.cms.web.vo.TypeEditVO;
import com.junzhiit.nengji.cms.web.vo.TypeGoodsVO;
import com.junzhiit.nengji.dao.ChainDAO;
import com.junzhiit.nengji.dao.ChainTypeDAO;
import com.junzhiit.nengji.dao.cache.SystemUserCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Chain;
import com.junzhiit.nengji.model.ChainType;

@Service
public class ChainTypeServiceImpl extends BaseServiceImpl implements ChainTypeService{
	
	@Autowired
	private ChainTypeDAO chainTypeDAO;
	
	@Autowired
	private SystemUserCacheDAO systemUserCacheDAO;
	
	@Autowired
	private ChainDAO chainDAO;
	
	@Value("${upload.temp}")
	private String uploadPath;

	@Value("${upload.mall.chain.goods.type}")
	private String chainTypePath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;
	
	@Override
	public ResultVO findAll(String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
		if (chain == null) {
			throw new ChainNotFoundException("连锁品牌不存在");
		}
		List<ChainType> lists = chainTypeDAO.findAll(chain.getId());
		List<ChainTypeVO> TypeVOlist = treeList(lists, Constants.ROOT_VALUE);
		result.setData(TypeVOlist);
		return result;
	}
	
	private List<ChainTypeVO> treeList(List<ChainType> typeList, String parentId) {
		List<ChainTypeVO> childTypeList = new ArrayList<ChainTypeVO>();
		
		for (ChainType type : typeList) {
			ChainTypeVO typeVO = new ChainTypeVO();
			BeanUtils.copyProperties(type, typeVO);
			String pid = type.getParentId();
			String id = type.getId();
			if (parentId.equals(pid)) {
				List<ChainTypeVO> children = treeList(typeList, id);
				typeVO.setChildren(children);
				childTypeList.add(typeVO);
			}
		}
		
		return childTypeList;
	}
	
	@Override
	public ResultVO getAllName(String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
		if (chain == null) {
			throw new ChainNotFoundException("连锁品牌不存在");
		}

		List<ChainType> types = chainTypeDAO.getAllName(chain.getId());
		List<TypeGoodsVO> typeGoodsVOs = new ArrayList<TypeGoodsVO>();
		for (ChainType type : types) {
			TypeGoodsVO typeGoodsVO = new TypeGoodsVO();
			BeanUtils.copyProperties(type, typeGoodsVO);
			typeGoodsVOs.add(typeGoodsVO);
		}

		result.setData(typeGoodsVOs);
		return result;
	}
	
	
	@Transactional
	@Override
	public ResultVO add(ChainTypeAddVO chainTypeAddVO) {

		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO
				.getHash(DIYKey.getSessionHashKey(chainTypeAddVO.getSessionId()), SystemUserSessionVO.class);
		Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
		if (chain == null) {
			throw new ChainNotFoundException("连锁品牌不存在");
		}

		ChainType chainType=new ChainType();
		BeanUtils.copyProperties(chainTypeAddVO, chainType);
		chainType.setChainId(chain.getId());

		int count = chainTypeDAO.getTypeExist(chainType);
		if (count > 0) {
			throw new TypeIsExistException("该分类名字已经存在");
		}

		String parentId = chainTypeAddVO.getParentId();
		String code = chainTypeDAO.getMaxCode(parentId);
		code = getTypeCode(code);

		String name = chainTypeAddVO.getName();
		String fullCode = null;
		String fullName = null;
		int level = 1;
		int sort = 1;

		if (Constants.ROOT_VALUE.equals(parentId)) {
			fullName = name;
			level = 1;
			fullCode = chainTypeDAO.getMaxFullCode(Constants.ROOT_VALUE);
			fullCode = getTypeFullCode(OrderNumberUtils.TYPE_NUMBER_PREFIX, fullCode);
			sort = chainTypeDAO.getMaxSort(Constants.ROOT_VALUE) + Constants.TYPE_SORT_ONE;

		} else {
			ChainType parentType = chainTypeDAO.query(parentId);
			String parentfullName = parentType.getFullName();

			String maxcode = chainTypeDAO.getMaxFullCode(parentId);
			fullCode = parentType.getFullCode() + getTypeFullCode(OrderNumberUtils.TYPE_NUMBER_PREFIX, maxcode);

			sort = chainTypeDAO.getMaxSort(parentId) + Constants.TYPE_SORT_ONE;

			if (StringUtils.isBlank(parentfullName)) {
				throw new TypeNotFoundException("顶级类未找到");
			}

			fullName = parentfullName + Constants.TYPE_FULLNAME_SEPARATOR + name;

			int parentlevel = parentType.getLevel();
			if (parentlevel <= 2) {
				level = parentlevel + 1;
			}

		}

		chainType.setCode(code);
		chainType.setFullCode(fullCode);
		chainType.setLevel(level);
		chainType.setFullName(fullName);
		chainType.setSort(sort);

		ChainType resultType = chainTypeDAO.insert(chainType);

		ResultVO result = new ResultVO();
		result.setData(resultType);

		return result;
	}
	
	
	private String getTypeCode(String maxCode) {
		int codeValue = 1;
		if (StringUtils.isNotBlank(maxCode)) {
			int currentMaxCode = Integer.valueOf(maxCode);
			codeValue += currentMaxCode;
		}
		String code = OrderNumberUtils.getSystemCode("", codeValue);
		return code;
	}

	private String getTypeFullCode(String prefix, String maxCode) {
		int codeValue = 1;
		if (StringUtils.isNotBlank(maxCode)) {
			int currentMaxCode = Integer.valueOf(maxCode.substring(maxCode.length() - 3, maxCode.length()));
			codeValue += currentMaxCode;
		}
		String code = OrderNumberUtils.getSystemCode(prefix, codeValue);
		return code;
	}

	@Override
	public ResultVO getGoodsType(String sessionId) {
		ResultVO result = new ResultVO();
		SystemUserSessionVO systemUserSessionVO = systemUserCacheDAO.getHash(DIYKey.getSessionHashKey(sessionId),
				SystemUserSessionVO.class);
		Chain chain = chainDAO.query(systemUserSessionVO.getSystemId());
		if (chain == null) {
			throw new ChainNotFoundException("连锁品牌不存在");
		}

		List<ChainType> types = chainTypeDAO.getGoodsType(chain.getId());
		List<TypeGoodsVO> typeGoodsVOs = new ArrayList<TypeGoodsVO>();
		for (ChainType type : types) {
			TypeGoodsVO typeGoodsVO = new TypeGoodsVO();
			BeanUtils.copyProperties(type, typeGoodsVO);
			typeGoodsVOs.add(typeGoodsVO);
		}
		result.setData(typeGoodsVOs);
		return result;
	}

	@Override
	public ResultVO delete(String id) {
		ResultVO result = new ResultVO();
		ChainType chainType = chainTypeDAO.query(id);

		if (chainType == null) {
			throw new TypeNotFoundException("该分类未找到");
		}

		chainTypeDAO.updateToDelete(id);
		List<ChainType> Types = chainTypeDAO.getChildId(id);

		List<String> idsArr = new ArrayList<String>();

		if (!Types.isEmpty()) {
			for (ChainType item : Types) {

				String childrenId = item.getId();
				idsArr.add(childrenId);

				List<ChainType> childrenTypes = chainTypeDAO.getChildId(childrenId);
				if (!childrenTypes.isEmpty()) {
					for (ChainType childrenitem : childrenTypes) {
						String childrenitemid = childrenitem.getId();
						idsArr.add(childrenitemid);
					}

				}

			}
		}

		String[] ids = idsArr.toArray(new String[] {});
		if (ids.length > 0 && ids != null) {
			boolean childrenflag = chainTypeDAO.batchUpdateToDelete(ids);
			result.setData(childrenflag);
		}

		return result;
	}
	
	@Override
	public ResultVO findbyid(String id) {
		ResultVO result = new ResultVO();
		ChainType chainType = chainTypeDAO.query(id);
		if (chainType == null) {
			throw new TypeNotFoundException("该分类未找到");
		}
		result.setData(chainType);
		return result;
	}
	
	
	@Transactional
	@Override
	public ResultVO update(TypeEditVO typeEditVO) {
		ResultVO result = new ResultVO();

		ChainType chainType = chainTypeDAO.query(typeEditVO.getId());
		if (chainType == null) {
			throw new TypeNotFoundException("该分类未找到");
		}

		String name = typeEditVO.getName();
		chainType.setName(name);
		int count = chainTypeDAO.getTypeExist(chainType);
		if (count > 0) {
			throw new TypeIsExistException("该分类名字已经存在");
		}

		// 更新该分类full_name
		String FullName = chainType.getFullName();
		String NewfullName = getNewFullName(FullName, name);
		chainType.setImgUrl(typeEditVO.getImgUrl());
		chainType.setFullName(NewfullName);

		chainTypeDAO.update(chainType);

		// 更新该分类下子类的full_name
		List<ChainType> typeResuls = new ArrayList<ChainType>();

		switch (chainType.getLevel()) {
		case 1:
			List<ChainType> types = chainTypeDAO.getChild(chainType.getId());

			for (ChainType t : types) {
				String fullName = t.getFullName();
				String NewFullName = getNewFullNameByFrist(fullName, name);
				t.setFullName(NewFullName);
				List<ChainType> typeChilds = chainTypeDAO.getChild(t.getId());

				for (ChainType tChild : typeChilds) {
					String ChildfullName = tChild.getFullName();
					String ChildNewFullName = getNewFullNameByFrist(ChildfullName, name);
					tChild.setFullName(ChildNewFullName);
				}

				typeResuls.addAll(typeChilds);
			}

			typeResuls.addAll(types);

			break;
		case 2:
			List<ChainType> typeseconds = chainTypeDAO.getChild(chainType.getId());
			for (ChainType t : typeseconds) {
				String fullName = t.getFullName();
				String NewFullName = getNewFullNameBySecond(fullName, name);
				t.setFullName(NewFullName);
			}
			typeResuls.addAll(typeseconds);

			break;
		default:
			break;
		}

		chainTypeDAO.batchUpdate(typeResuls,true);

		return result;
	}
	
	private String getNewFullName(String fullName, String name) {
		int beginindex = fullName.lastIndexOf(">") < 0 ? 0 : fullName.lastIndexOf(">") + 1;
		String old = fullName.substring(beginindex, fullName.length());
		String NewFullName = fullName.replace(old, name);
		return NewFullName;
	}

	private String getNewFullNameByFrist(String fullName, String name) {
		int beginindex = fullName.indexOf(">") < 0 ? 0 : fullName.indexOf(">");
		String old = fullName.substring(0, beginindex);
		String NewFullName = fullName.replaceFirst(old, name);
		return NewFullName;
	}

	private String getNewFullNameBySecond(String fullName, String name) {
		int beginIndex = fullName.indexOf(">") < 0 ? 0 : fullName.indexOf(">") + 1;
		int endIndex = fullName.lastIndexOf(">") < 0 ? 0 : fullName.lastIndexOf(">");
		String old = fullName.substring(beginIndex, endIndex);
		String NewFullName = fullName.replaceFirst(old, name);
		return NewFullName;
	}
	
	@Override
	public ResultVO getGoodsAuditType(String chainId) {
		ResultVO result = new ResultVO();
		List<ChainType> types = chainTypeDAO.getGoodsAuditType(chainId);
		List<TypeGoodsVO> typeGoodsVOs = new ArrayList<TypeGoodsVO>();
		for (ChainType type : types) {
			TypeGoodsVO typeGoodsVO = new TypeGoodsVO();
			BeanUtils.copyProperties(type, typeGoodsVO);
			typeGoodsVOs.add(typeGoodsVO);
		}
		result.setData(typeGoodsVOs);
		return result;
	}
	
	@Override
	public ResultVO updateTypeImage(TypeEditVO typeEditVO){
		ResultVO result=new ResultVO();
		ChainType type=new ChainType();
		BeanUtils.copyProperties(typeEditVO, type);
		chainTypeDAO.update(type);
		
		if(StringUtils.isNotBlank(typeEditVO.getImgUrl())){
			//FileUtil.moveFile(uploadPath + typeEditVO.getImgUrl(), chainTypePath);
			boolean is = AliyunOSSClientUtil.moveFile(backetName,typeEditVO.getImgUrl(), chainTypePath, uploadPath);
			if(is){
				AliyunOSSClientUtil.removeFile(backetName, uploadPath+typeEditVO.getImgUrl());
			}
		}
		
		result.setData(type);
		return result;
	}
	
	@Override
	public ResultVO deleteTypeImage(String id){
		ResultVO result=new ResultVO();
		ChainType chainType=chainTypeDAO.query(id);
		if (chainType == null) {
			throw new TypeNotFoundException("该分类未找到");
		}
		if(StringUtils.isNotBlank(chainType.getImgUrl())){
			AliyunOSSClientUtil.removeFile(backetName, uploadPath+chainType.getImgUrl());
		}
		
		chainType.setImgUrl(null);
		chainTypeDAO.update(chainType,true);
		result.setData(chainType);
		return result;
	}
	
}
